import React from 'react'
import { Card, Button, Table, Divider, Row, Col, InputNumber, Modal, Form, Input, Select } from 'antd'
import DescriptionList from 'components/DescriptionList'
import styles from './index.less'
import {
  contractChangeType,
  contractChangeBusinessType,
  contractChangeReason
} from 'utils/enumConfig'
import moment from 'moment'
import { LwjArea }  from 'components'
import LwjUpload from 'components/LwjUpload/LwjUpload'
import { validatorCharacters ,validateMobile} from 'utils/utils';

const FormItem = Form.Item

const EditModal = ({
  currentItem,
  dispatch,
  form: {
    getFieldDecorator,
    validateFields,
    setFieldsValue,
    getFieldValue,
    resetFields
  },
  queryParam,
  record,
  contractItems,
  contractModalVisible,
  contractSelectedRowKeys,
  // contractItem,
  changeType,
  ...editModalProps,
}) => {
  const FormItem = Form.Item
  const Option = Select.Option
  const { Description } = DescriptionList
  const contractItem = currentItem;
  const toEdit = () => {
    validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'orderChangeApply/update',
          payload: {
            id: record.id,
            version: record.version,
            values
          }
        })
      }
    })
  }

  const xlsProps = {
    maxfile:1,
    target: '/services/upload/order',
    uploadIcon: 'upload',
    fileType: '',
    onChange(value) {
    },
    showUploadList: true
  }


  const formItemLayout = {
    labelCol: {
      xs: { span: 8, offset: 0 },
      sm: { span: 8, offset: 0 },
    },
    wrapperCol: {
      xs: { span: 8, offset: 0 },
      sm: { span: 8, offset: 0 },
    },
  }

  const changeAmountFunc = (value, orderAmount, changeAmount) => {
    let changedAmount = 0
    switch (value) {
      case 'SUPPLEMENT':
        changedAmount = parseFloat(orderAmount) + parseFloat(changeAmount)
        setFieldsValue({
          'changedAmount': changedAmount
        })
        break
      case 'REFUND':
        changedAmount = parseFloat(orderAmount) - parseFloat(changeAmount)
        if (changedAmount > 0) {
          setFieldsValue({
            'changedAmount': changedAmount
          })
        } else {
          Modal.warning({
            title: '错误',
            content: '退款时变更金额必须小于原合同金额'
          })
          resetFields(['changeAmount', 'changedAmount'])
          break
        }
    }
  }
  const cancel = () => {
    dispatch({
      type: 'orderChangeApply/hideEditModal',
      payload: {}
    })
  }
  const optionBuilder = (type) => {
    let option = []
    Object.keys(type).forEach((key) => { option.push(<Option key={key} value={key}>{type[key]}</Option>) })
    return option
  }
  return (
    <div>
      <Modal {...editModalProps} onOk={() => toEdit()}>
        <Form layout="horizontal">
          <Row>
            <Col span={12}>
              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="变更业务类型">
                  {getFieldDecorator('contractChangeBusinessType', {
                    rules: [{ required: true, message: '变更业务类型必须选择!' }],
                    initialValue: contractItem.contractChangeBusinessType
                  })(<Select onChange={(value) => {
                    const orderAmount = getFieldValue('orderAmount')
                    const changeAmount = getFieldValue('changeAmount') || 0

                    changeAmountFunc(value, orderAmount, changeAmount)

                  }}>
                    {optionBuilder(contractChangeBusinessType)}
                  </Select>)}
                </FormItem>}


              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="原合同总金额">
                  {getFieldDecorator('preOrderAmount', {
                    rules: [{ required: true, message: '原合同总金额必须填写!' }],
                    initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.preOrderAmount : ''
                  })(<Input disabled={true} />)}
                </FormItem>}

              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="装修返点金额">
                  {getFieldDecorator('decorationRebateAmount', {
                    rules: [{ required: true, message: '装修返点金额必须填写!' }],
                    initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.decorationRebateAmount : ''
                  })(<Input disabled={true} />)}
                </FormItem>}

              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="样柜返点金额">
                  {getFieldDecorator('cabinetRebateAmount', {
                    rules: [{ required: true, message: '样柜返点金额必须填写!' }],
                    initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.cabinetRebateAmount : ''
                  })(<Input disabled={true} />)}
                </FormItem>}

              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="活动优惠金额">
                  {getFieldDecorator('eventsAmount', {
                    rules: [{ required: true, message: '活动优惠金额必须填写!' }],
                    initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.eventsAmount : ''
                  })(<Input disabled={true} />)}
                </FormItem>}

              {contractItem.id && changeType === 'INFORMATION' && <FormItem {...formItemLayout} hasFeedback label="收货人">
                {getFieldDecorator('consigneeName', {
                  rules: [
                    {
                      required: true,
                      message: '收货人姓名不能为空',
                      whitespace: true
                    },
                    {
                      max:5,
                      message: '收货人姓名长度不能大于5',
                      whitespace: true
                    }
                    ,{
                      validator:validatorCharacters
                    }
                  ],
                  initialValue: contractItem ? contractItem.consigneeName : ''
                })(<Input />)}
              </FormItem>}

              {contractItem.id && changeType === 'INFORMATION' && <FormItem {...formItemLayout} hasFeedback label="收货人电话">
                {getFieldDecorator('consigneePhoneNum', {
                  rules: [
                    {
                      required: true,
                      message: '请输入正确的收货人电话',
                      whitespace: true
                    }, {
                      validator: validateMobile
                    }
                  ],
                  initialValue: contractItem ? contractItem.consigneePhoneNum : ''
                })(<Input />)}
              </FormItem>}

              {contractItem.id && changeType === 'INFORMATION' && !_.isEmpty(contractItem.consigneeRegion) &&
                <FormItem {...formItemLayout} label="收货人地址">
                  {getFieldDecorator('consigneeRegion', {
                    rules: [
                      {
                        required: true,
                        message: '请选择收货人地址',
                        type: 'array'
                      }
                    ],
                    initialValue: contractItem ? contractItem.consigneeRegion : []
                  })(<LwjArea width={'100%'} />)}
                </FormItem>}

              {contractItem.id && changeType === 'INFORMATION' &&
                <FormItem {...formItemLayout} hasFeedback label="收货人详细地址">
                  {getFieldDecorator('address', {
                    rules: [{ required: true, message: '收货人详细地址必须填写!' }],
                    initialValue: contractItem ? contractItem.address : ''
                  })(<Input />)}
                </FormItem>}
            </Col>

            <Col span={12}>
              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="原合同金额">
                  {getFieldDecorator('orderAmount', {
                    rules: [{ required: true, message: '原合同金额必须填写!' }],
                    initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.orderAmount : ''
                  })(<Input disabled={true} />)}
                </FormItem>}

              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="变更金额">
                  {getFieldDecorator('changeAmount', {
                    validateTrigger: ['onBlur', 'onSubmit'],
                    rules: [{ required: true, message: '变更金额必须填写!' }, {
                      validator: (rule, value, callback) => {
                        const orderAmount = getFieldValue('orderAmount')
                        const changeAmount = value || 0
                        if (isNaN(value) || value <= 0) {
                          callback('请输入大于0的数字')

                          return
                        }

                        // 判断是补款还是退款
                        let contractChangeBusinessType = getFieldValue('contractChangeBusinessType')
                        if (typeof contractChangeBusinessType === 'undefined') {
                          Modal.warning({
                            title: '提示',
                            content: '变更业务类型未选择'
                          })
                          resetFields(['changeAmount'])
                          return
                        }

                        changeAmountFunc(contractChangeBusinessType, orderAmount, changeAmount)
                        callback()
                      }
                    }],
                    initialValue: contractItem.changeAmount
                  })(<InputNumber />)}
                </FormItem>}

              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} hasFeedback label="变更后合同金额">
                  {getFieldDecorator('changedAmount', {
                    rules: [{ required: true, message: '变更后合同金额必须填写!' }],
                    initialValue: contractItem.changedAmount
                  })(<Input disabled={true} />)}
                </FormItem>}


              {contractItem.id && changeType === 'AMOUNT' && <FormItem {...formItemLayout} hasFeedback label="变更原因">
                {getFieldDecorator('contractChangeReason', {
                  rules: [{ required: true, message: '变更业务类型必须选择!' }],
                  initialValue: contractItem.contractChangeReason
                })(<Select>
                  {optionBuilder(contractChangeReason)}
                </Select>)}
              </FormItem>}

              {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
                <FormItem {...formItemLayout} label="报价方案">
                  {getFieldDecorator('quoteAttachment', {
                    rules: [{ required: true, message: '报价方案必须上传!' }],
                    initialValue: contractItem.quoteAttachment
                  })(<LwjUpload {...xlsProps}
                    fileLists={contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.quoteAttachment : ''} />)}
                </FormItem>}

              {contractItem.id && changeType === 'INFORMATION' && contractItem.productType !== 'END' &&
                <FormItem {...formItemLayout} label="设计方案">
                  {getFieldDecorator('designAttachment', {
                    rules: [{ required: true, message: '设计方案必须上传!' }],
                    initialValue: contractItem.designAttachment || ''
                  })(<LwjUpload {...xlsProps} fileLists={contractItem.designAttachment || ''} />)}
                </FormItem>}

              {contractItem.id && changeType === 'INFORMATION' && contractItem.productType === 'END' &&
                <FormItem {...formItemLayout} label="成品清单">
                  {getFieldDecorator('endOrderAttachment', {
                    rules: [{ required: true, message: '成品清单必须上传!' }],
                    initialValue: contractItem.endOrderAttachment || ''
                  })(<LwjUpload {...xlsProps} fileLists={contractItem.endOrderAttachment || ''} />)}
                </FormItem>}

              {contractItem.id && <FormItem {...formItemLayout} hasFeedback label="备注">
                {getFieldDecorator('des', {
                  rules: [],
                  initialValue: contractItem.des
                })(<Input />)}
              </FormItem>}
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  )
}

export default Form.create()(EditModal)
